package com.ymkj.testdemo.list;

import java.util.*;

public class RemoveByIterator {

    public static void main(String[] args) {

        List<Integer> arrList1 = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            arrList1.add(i);
        }

        List<Integer> linList1 = new LinkedList<>();
        for (int i = 0; i < 100000; i++) {
            linList1.add(i);
        }

        List<Integer> arrList2 = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            arrList2.add(i);
        }

        List<Integer> linList2 = new LinkedList<>();
        for (int i = 0; i < 100000; i++) {
            linList2.add(i);
        }

        removeEvens(arrList1, "ArrayList");
        removeEvens(linList1, "LinkedList");
        removeEvensByIterator(arrList2, "ArrayList");
        removeEvensByIterator(linList2, "LinkedList");

    }

    public static void removeEvensByIterator(List<Integer> lst, String name) {//利用迭代器remove偶数
        long sTime = new Date().getTime();
        Iterator<Integer> itr = lst.iterator();
        while (itr.hasNext()) {

            if (itr.next() % 2 == 0)
                itr.remove();
        }

        System.out.println(name + "使用迭代器时间:" + (new Date().getTime() - sTime) + "毫秒");
    }

    public static void removeEvens(List<Integer> list, String name) {//不使用迭代器remove偶数
        long sTime = new Date().getTime();
        int i = 0;
        while (i < list.size()) {

            if (list.get(i) % 2 == 0) {
                list.remove(i);
            } else {
                i++;
            }
        }

        System.out.println(name + "不使用迭代器的时间" + (new Date().getTime() - sTime) + "毫秒");
    }
}